<?php

namespace App\Repositories;

use App\Models\User;

class UserRepository
{
    /**
     * 根据属性获取单个用户
     *
     * @param string $attribute
     * @param string $value
     * @return null|\Illuminate\Database\Eloquent\Model
     */
    public function getByAttribute($attribute, $value)
    {
        if (!in_array($attribute, ['id', 'name', 'email', 'mobile', 'api_token'])) {
            return null;
        }
        return User::where($attribute, $value)->first();
    }

    /**
     * 创建用户
     *
     * @param array $attributes
     * @return $this|\Illuminate\Database\Eloquent\Model
     */
    public function create(array $attributes)
    {
        $user = User::create($attributes);
        return $user;
    }

    /**
     * 更新用户信息
     *
     * @param array $attributes
     * @param User $user
     * @return bool
     */
    public function update(array $attributes, User $user)
    {
        return $user->update($attributes);
    }

    /**
     * 删除用户
     *
     * @param User $user
     * @throws \Exception
     */
    public function destroy(User $user)
    {
        $user->delete();
    }

    /**
     * 获取用户列表（分页）
     *
     * @param array $condition
     * @param array $with
     * @param string $order_by_column
     * @param string $order_by_direction
     * @param int $per_page
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function paginate($condition = [], $with = [], $order_by_column = 'id', $order_by_direction = 'desc', $per_page = 20)
    {
        $user = User::with($with)->orderBy('users.enabled', 'desc')->orderBy($order_by_column, $order_by_direction);
        if (isset($condition['name'])) {
            $user->where('name', 'like', '%' . $condition['name'] . '%');
        }
//        if (isset($condition['mobile']) && is_numeric($condition['mobile'])) {
//            if (is_mobile($condition['mobile'])) {
//                $user->where('mobile', $condition['mobile']);
//            } else {
//                $user->where('mobile', 'like', '%' . $condition['mobile'] . '%');
//            }
//        }

        if (isset($condition['mobile'])) {
            $user->where('mobile', 'like', '%' . $condition['mobile'] . '%');
        }

        if (isset($condition['email'])) {
            $user->where('mobile', $condition['email']);
        }
        if (isset($condition['enabled']) && is_numeric($condition['enabled'])) {
            $user->where('enabled', $condition['enabled']);
        }
        return $user->paginate($per_page);
    }
}
